<template>
  <div>
    <a-row :gutter="[20, 0]">
      <a-col :span="8">
        <a-card :body-style="{padding: '24px 32px'}" :bordered="false" class="menu">
          <div style="display: flex;align-items: center;justify-content: space-between">
            <div style="flex: 1">菜单管理</div>
            <div style="flex: 1;text-align: right" class="handle">
              <a-icon type="delete"  @click="deleteMenuHandle"/>
              <a-icon type="edit"  @click="updateMenuHandle"/>
              <a-icon type="plus" @click="addMenuHandle"/>
            </div>
          </div>
          <a-row :gutter="[20, 20]" style="margin-top: 20px">
            <a-col :span="12">
              <a-select  v-model="query.appInfoCode" placeholder="请选择系统类型"  style="width: 100%" @change="handleChangeApp">
                <a-select-option v-for="app in appList" :key="app.code">
                  {{ app.name }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="12">
              <a-select v-model="query.channelType"  style="width: 100%"  placeholder="请选择渠道类型"  @change="handleChangeChannel">
                <a-select-option v-for="app in channelList" :key="app.type">
                  {{ app.name }}
                </a-select-option>
              </a-select>
            </a-col>
            <div style="clear: both">
              <a-tree
                  :tree-data="treeData"
                  :replaceFields="replaceFields"
                  :defaultExpandAll="true"
                  @select="selectTreeNode"
              >
              </a-tree>
            </div>
          </a-row>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
          <div style="display: flex;align-items: center;justify-content: space-between">
            <div style="flex: 1">功能列表</div>
            <div style="flex: 1;text-align: right; cursor: pointer" class="handle">
              <!-- <a-icon type="plus" @click="addResourceHandle"/> -->
         <a href="javascript:;" style="margin: 0 10px 0 0" @click="addResourceHandle">新增</a>

            </div>
          </div>
          <div style="margin-top: 20px">
            <a-table :columns="columns" :data-source="tableData" :pagination="pagination">
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <a href="javascript:;" style="margin: 0 10px"  @click="updateResourceHandle(text, record, index)"> 编辑</a>
                  <a href="javascript:;" @click="deleteResourceHandle(text, record, index)">删除</a>
                </div>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-modal title="Title" width="40%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible=false">
      <a-form-model ref="ruleForm" :model="menuObj" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item ref="parentName" label="父级名称" prop="parentName">
          {{parentObj.name}}
        </a-form-model-item>
        <a-form-model-item ref="name" label="名称" prop="name">
          <a-input v-model="menuObj.name" placeholder="请输入" @blur=" () => {$refs.name.onFieldBlur();}"/>
        </a-form-model-item>
        <a-form-model-item ref="resKey" label="资源标识" prop="resKey">
          <a-input v-model="menuObj.resKey" placeholder="请输入" @blur=" () => {
            $refs.resKey.onFieldBlur();
            menuObj.resKey = menuObj.resKey.replace(/\s*/g,'');
            }"/>
        </a-form-model-item>
        <a-form-model-item ref="icon" label="图标" prop="icon">
          <a-input v-model="menuObj.icon" placeholder="请输入" @blur=" () => {$refs.icon.onFieldBlur();}"/>
        </a-form-model-item>
        <a-form-model-item ref="sort" label="排序" prop="sort">
          <a-input-number v-model="menuObj.sort" placeholder="请输入" @blur=" () => {$refs.icon.onFieldBlur();}"/>
        </a-form-model-item>
        <a-form-model-item ref="isShow" label="是否显示在菜单" prop="isShow">
          <a-radio-group v-model="menuObj.isShow">
            <a-radio :value="0">
              显示
            </a-radio>
            <a-radio :value="1">
              不显示
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-input v-model="menuObj.remark" placeholder="请输入" type="textarea" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {
  getResource,
  getResourceList,
  getUserAppList,
  resourceDelete,
  resourceSave,
  resourceUpdate
} from "../../services/system";
export default {
  name: "MenuManage",
  data() {
    return {
      appList: [],
      channelList: [],
      query: {
        appInfoCode: null,
        channelType: null
      },
      searchValue: '',
      treeData: [],
      replaceFields: {
        title: 'name',
        key: 'id'
      },
      visible: false,
      confirmLoading: false,
      parentObj: {},
      menuObj: {
        name: null,
        parentCode: null,
        type: 'MENU',
        channelType: null,
        appInfoCode: null,
        resKey: null,
        icon: null,
        remark: null,
        sort: null,
        isShow: null,
        target: null
      },
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        resKey: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        sort: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        isShow: [
          { required: true, message: '请选择', trigger: 'change' },
        ]
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
        },
        {
          title: '资源标识',
          dataIndex: 'resKey',
        },
        {
          title: '图标',
          dataIndex: 'icon',
        },
        {
          title: '排序',
          dataIndex: 'sort',
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'Action',
          scopedSlots: { customRender: 'operation' },
        }
      ],
      tableData: []
    };
  },
  created() {
    this.getSystemChannl()
  },
  methods: {
    getSystemChannl(){
      getUserAppList().then(res=>{
        this.appList = res.data.data.rows
        if(this.appList && this.appList.length>0){
          this.parentObj = this.appList[0]
          this.query.appInfoCode = this.appList[0].code
          this.channelList = this.appList[0].channelInfos
          if(this.channelList && this.channelList.length>0) {
            this.query.channelType = this.channelList[0].type
          }
        }
        this.getMenus()
      })
    },
    handleChangeApp (value) {
      this.query.channelType= null
      let obj = this.appList.find(item=>item.code===value)
      this.parentObj = obj
      this.channelList = obj.channelInfos
      if(this.channelList && this.channelList.length>0) {
        this.query.channelType = this.channelList[0].type
      }
      this.getMenus()
    },
    handleChangeChannel (value){
      if(value){
        this.getMenus()
      }
    },
    getMenus(){
      getResourceList({
        orderBy: 'sort',
        orderDir: 'asc',
        appInfoCode: this.query.appInfoCode,
        channelType: this.query.channelType,
        type: 'MENU'
      }).then(res=>{
        this.treeData = res.data.data.rows
      })
    },
    selectTreeNode (selectedKeys, e) {
      this.parentObj = e.node.dataRef
      this.getOperation()
    },
    addMenuHandle(){
      this.dataType = 0
      this.menuObj = {
        name: null,
        parentCode: this.parentObj.parentCode?this.parentObj.code: '',
        type: 'MENU',
        channelType: this.query.channelType,
        appInfoCode: this.query.appInfoCode,
        resKey: null,
        icon: null,
        remark: null,
        sort: null,
        isShow: null,
        target: null
      }
      this.visible = true
    },
    getMenuById(id){
      getResource(id).then(res=>{
        this.menuObj = Object.assign({}, this.menuObj, res.data.data)
      })
    },
    updateMenuHandle () {
      if(this.parentObj.parentCode){
        this.getMenuById(this.parentObj.id)
        this.visible = true
      }else{
        this.$message.error('请选择要编辑的菜单');
      }
    },
    deleteMenuHandle (){
      if(this.parentObj.parentCode){
        let vm = this
        this.$confirm({
          title: '您确定要删除该数据？',
          content: '数据删除后不可恢复',
          onOk() {
            return new Promise((resolve, reject) => {
              resourceDelete(vm.parentObj.id).then(res=>{
                if(res.data.status==0){
                  vm.getMenus()
                  resolve()
                }else{
                  reject(res.data.msg)
                }
              })
            })
          },
          onCancel() {},
        });
      }else{
        this.$message.error('请选择要删除的菜单');
      }
    },
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.menuObj.resKey=this.menuObj.resKey.replace(/(^\s*)|(\s*$)/g, "");

          this.confirmLoading = true
          let handle
          if(this.menuObj.id){
            handle = resourceUpdate(this.menuObj.id,this.menuObj)
          }else{
            handle = resourceSave(this.menuObj)
          }
          handle.then(res=>{
            this.confirmLoading = false
            if(res.data.status==0){
              this.visible = false
              if(this.dataType==0){
                this.getMenus()
              }else{
                this.getOperation()
              }

            }
          }).catch(error=>{
            console.log(error)
            this.confirmLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getOperation(){
      getResourceList({
        page: this.pagination.current,
        perPage: this.pagination.pageSize,
        orderBy: 'sort',
        orderDir: 'asc',
        appInfoCode: this.query.appInfoCode,
        channelType: this.query.channelType,
        type: 'OPERATION',
        parentCode: this.parentObj.code
      }).then(res=>{
        let data = res.data.data.rows
        data.forEach(item=>{
          item.children = null
        })
        this.tableData = data
        this.pagination.total = res.data.data.count
      })
    },
    addResourceHandle () {
      if(this.parentObj.parentCode){
        this.dataType = 1
        this.menuObj = {
          name: null,
          parentCode: this.parentObj.parentCode?this.parentObj.code: '',
          type: 'OPERATION',
          channelType: this.query.channelType,
          appInfoCode: this.query.appInfoCode,
          resKey: null,
          icon: null,
          remark: null,
          sort: null,
          isShow: null,
          target: null
        }
        this.visible = true
      }else{
        this.$message.error('请选择一个菜单');
      }
    },
    updateResourceHandle (text, item) {
      console.log(item)
      this.dataType = 1
      this.getMenuById(item.id)
      this.visible = true
    },
    deleteResourceHandle (text, item) {
      let vm = this
      this.$confirm({
        title: '您确定要删除该数据？',
        content: '数据删除后不可恢复',
        onOk() {
          return new Promise((resolve, reject) => {
            resourceDelete(item.id).then(res=>{
              if(res.data.status==0){
                vm.getOperation()
                resolve()
              }else{
                reject(res.data.msg)
              }
            })
          })
        },
        onCancel() {},
      });
    }
  },
}
</script>

<style lang="less" scoped>
.menu {
  .handle {
    i {
      margin: 0 10px;
      font-size: 16px;
      cursor: pointer;
    }
  }
}
</style>
